# coding: utf-8
from typing import List

from sqlalchemy import Column, String, TEXT
from sqlalchemy.orm import Session

from ..db import DbBase
from ..utils.api_models import BookItemModel


class TableBookShelf(DbBase):
    __tablename__ = 'book_shelf'
    title = Column(String(255), nullable=False)
    desc = Column(TEXT, nullable=True)
    cover = Column(TEXT, nullable=True)
    tags = Column(String(255), nullable=True)
    info_url = Column(TEXT, nullable=False, unique=True, primary_key=True)
    source = Column(String(255), nullable=False)


def is_book_shelf_exist(info_url: str, *, session: Session) -> bool:
    return session.query(TableBookShelf).filter_by(info_url=info_url).count() > 0


def add_book_shelf(model: BookItemModel, *, session: Session):
    if is_book_shelf_exist(model.info_url, session=session):
        return
    table = TableBookShelf(
        title=model.title,
        desc=model.desc,
        cover=model.cover,
        tags=model.tags,
        info_url=model.info_url,
        source=model.source.name,
    )
    session.add(table)
    session.commit()


def delete_book_shelf(info_url: str, *, session: Session):
    session.query(TableBookShelf).filter_by(info_url=info_url).delete()
    session.commit()


def read_all_book_shelf(session: Session) -> List[BookItemModel]:
    result = session.query(TableBookShelf).all()
    return [BookItemModel(
        title=item.title,
        desc=item.desc,
        cover=item.cover,
        tags=item.tags,
        info_url=item.info_url,
        source=item.source,
    ) for item in result]
